import permissionApi from '@/api/bms/permission'
import serviceUtil from '@/utils/service'
import { Modal } from 'view-design'
import { setToken, removeLoginMsg, setUser, getUser, getToken } from '@/utils/auth'
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'

function convertMenuData(menus) {
  if (menus) {
    return menus.map(menu => {
      const convertMenu = {
        path: menu.item && menu.item.route,
        title: menu.item && menu.item.moduleName,
        idPath: menu.item && menu.item.idPath,
        moduleId: menu.item && menu.item.moduleId
      }
      const moduleIcon = menu.item && menu.item.moduleIcon
      if (moduleIcon) {
        // 如果是svg开头,配置svg图标
        if (moduleIcon.indexOf('svg-') === 0) {
          convertMenu.iconSvg = moduleIcon.substring(4)
        } else {
          convertMenu.icon = moduleIcon
        }
      }
      if (menu.menus) {
        convertMenu.children = convertMenuData(menu.menus)
      }
      return convertMenu
    })
  } else {
    return [
      {
        path: '/index',
        title: '首页',
        idPath: 'index',
        moduleId: 'index',
        icon: 'icon-home'
      }
    ]
  }
}

const bms = {
  state: {
    token: getToken(),
    userAreaBranchTree: [],
    userBelongBranch: [],
    permissionMenu: [],
    permissionButton: [],
    orgTree: [],
    orgNameObj: null,
    employee: getUser()
  },

  mutations: {
    // 更新页面切换状态
    UPDATE_USER_AREA_BRANCH_TREE: (state, data) => {
      state.userAreaBranchTree = data
    },
    UPDATE_USER_BELONGS_BRANCES: (state, data) => {
      state.userBelongBranch = data
    },
    UPDATE_PERMISSION_MENU: (state, data) => {
      state.permissionMenu = data
    },
    UPDATE_EMPLOYEE: (state, data) => {
      state.employee = data
    },
    UPDATE_PERMISSION_BUTTON: (state, data) => {
      state.permissionButton = data
    },
    UPDATE_ORG_TREE: (state, data) => { // 分支树数据
      state.orgTree = data
    },
    CLEAR_LOGIN_MSG: (state) => {
      state.userAreaBranchTree = []
      state.userBelongBranch = []
      state.permissionMenu = []
      state.permissionButton = []
      state.employee = null
      state.orgTree = []
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },

  actions: {
    // 保存bms信息
    saveBmsMsg({ commit }, data) {
      commit('SET_TOKEN', data.token)
      setToken(data.token)
      commit('UPDATE_EMPLOYEE', data)
      setUser(data)
    },
    async bmsLogin({ dispatch, commit }, userInfo) {
      // 登录
      const username = userInfo.username.trim()
      const password = userInfo.password
      try {
        const publicKey = await permissionApi.getPublicKey().then(serviceUtil.filterBmsBackendData)
        const encrypt = new JSEncrypt()
        encrypt.setPublicKey(publicKey)
        const loginMsg = await permissionApi.login({
          account: username,
          password: encrypt.encrypt(password),
          publicKey: publicKey,
          useSso: true
        }).then(serviceUtil.filterBmsBackendData)
        return new Promise((resolve, reject) => {
          if (loginMsg.cipherLevel === 0 || loginMsg.cipherLevel === 1) {
            Modal.confirm({
              title: '警告',
              content: '密码强度过低，跳往修改密码界面',
              onOk: () => {
                loginMsg.redirectCipherUri = loginMsg.redirectCipherUri.replace('oms', 'bms')
                window.location.href = `${loginMsg.redirectCipherUri}?tokenId=${loginMsg.token}&username=${username}&redirectUrl=${escape(location.href)}`
              },
              onCancel: () => {
                reject('密码强度过低，请修改密码')
              }
            })
          } else {
            window.zhnxSSO.saveRefreshToken(loginMsg.refreshToken).catch(error => console.log(error))
            dispatch('saveBmsMsg', loginMsg)
            resolve()
          }
        })
      } catch (e) {
        return Promise.reject(e)
      }
    },
    bmsLogout({ commit }) {
      /** 清空store中的数据 */
      commit('CLEAR_LOGIN_MSG')
      return new Promise((resolve, reject) => {
        // 清除用户登录信息
        removeLoginMsg()
        resolve()
      })
    },
    // 获取bms系统参数
    getBmsParams({ dispatch }) {
      return Promise.all([dispatch('getUserMenu'), dispatch('getUserButton'), dispatch('getUserAreaBranchTree'), dispatch('getOrgTree')])
    },
    // 获取用户菜单
    getUserMenu({ commit }) {
      return permissionApi.getUserMenu().then(serviceUtil.filterBmsBackendData).then(res => {
        const convertMenus = convertMenuData(res && res.menus)
        commit('UPDATE_PERMISSION_MENU', convertMenus)
      })
    },
    // 获取用户按钮权限
    getUserButton({ commit }) {
      return permissionApi.getUserButton().then(serviceUtil.filterBmsBackendData).then(res => {
        commit('UPDATE_PERMISSION_BUTTON', res)
      })
    },
    // 设置当前登录人的区域分支树
    getUserAreaBranchTree({ commit }) {
      return permissionApi.getUserAreaBranchTree().then(serviceUtil.filterBmsBackendData).then(res => {
        commit('UPDATE_USER_AREA_BRANCH_TREE', res)
      })
    },
    // 获取组织机构树
    async getOrgTree({ commit }) {
      return permissionApi.getOrgTree().then(serviceUtil.filterBmsBackendData).then(res => {
        commit('UPDATE_ORG_TREE', res)
      })
    }
  }
}

export default bms
